#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：      connection.py
   Remark :         MySQL连接管理
-------------------------------------------------
"""

# 标准库导入
import os
import logging
from typing import Optional

# 第三方库导入
import pymysql
from dbutils.pooled_db import PooledDB  # 用于连接池


# 本地应用/库导入
from hellchin.db.mysql.config import MysqlConfig
from hellchin.util.logger import log as logger

# Configure logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)




class MySqlConnection:

    def __init__(
            self,
            host: Optional[str] = None,  # 默认 None，调用时可省略
            user: Optional[str] = None,  # 默认 None，调用时可省略
            password: Optional[str] = None,  # 默认 None，调用时可省略
            database: Optional[str] = None,  # 默认 None，调用时可省略
            port: Optional[int] = None,  # 默认 None，调用时可省略
            charset: str = "utf8mb4",  # 默认不为空
            max_retries: int = 3,  # 默认不为空
            pool_size: int = 10  # 默认不为空
    ):
        """
        初始化 MySQL 连接池。

        :param host: MySQL 主机地址
        :param port: MySQL 端口
        :param user: MySQL 用户名
        :param password: MySQL 密码
        :param database: 默认数据库
        :param charset: 字符集
        :param max_retries: 最大重试次数
        :param pool_size: 连接池大小
        """
        self.host = host or MysqlConfig.host
        self.user = user or MysqlConfig.user
        self.password = password or MysqlConfig.password
        self.db = database or MysqlConfig.database
        self.port = port or MysqlConfig.port
        self.connection = None

        # 使用连接池
        try:
            self.pool = PooledDB(
                creator=pymysql,
                maxconnections=pool_size,
                mincached=1,
                blocking=True,
                ping=0,
                host=self.host,
                port=self.port,
                user=self.user,
                password=self.password,
                database=self.db,
                charset=charset,
                cursorclass=pymysql.cursors.DictCursor,  # 返回字典形式结果
            )
            logger.info(f"Connected to MySQL at {self.host}:{self.port} (database={self.db})")

        except pymysql.Error as e:
            logger.error(f"MySQL connection error: {e}")
            raise RuntimeError(
                f"Failed to connect to MySQL server at {self.host}:{self.port}. "
                f"Please check:\n"
                f"1. MySQL server is running\n"
                f"2. Connection parameters are correct\n"
                f"3. Network connectivity to the server\n"
                f"Original error: {e}"
            )
        except Exception as e:
            logger.error(f"Unexpected error initializing MySQL connection pool: {e}")
            raise RuntimeError(f"Unexpected error occurred during connection pool initialization: {e}")


    def connect(self):
        """
        创建 MySQL 连接
        """
        if self.connection is None:
            try:
                self.connection = self.pool.connection()
                print(f"Connected to MySQL database {self.db} at {self.host}:{self.port}")
            except pymysql.MySQLError as e:
                print(f"Error connecting to MySQL: {e}")
                raise  ConnectionError("Error connecting to MySQL. Please check your connection settings.")
            except Exception as e:
                print(f"Error connecting to MySQL: {e}")
                raise  RuntimeError("Unexpected error occurred while connecting to MySQL.")

        return self.connection

    def close(self):
        """ 关闭 MySQL 连接 """
        if self.connection:
            self.connection.close()
            print(f"Connection to {self.host} closed.")
        else:
            print("No active connection to close.")


if __name__ == '__main__':
    MySqlConnection().connect()